// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
//商户配置
const mch_id = '1642611741' //商户号
//数据库服务
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let subMchId = mch_id //微信支付分配的子商户号
  let nonceStr = Math.random().toString(36).substr(2, 13) //随机字符串，不长于32位。推荐随机数生成算法
  let {
    outRefundNo,
    outTradeNo,
    transactionId,
    refundId
  } = event

  //查询交易单
  const result = await cloud.cloudPay.queryRefund({
    subMchId,
    outRefundNo,
    outTradeNo,
    transactionId,
    refundId,
    nonceStr,
  })

  if (result.returnCode != "SUCCESS") {
    return {
      errCode: result.returnCode,
      errMsg: result.returnMsg
    }
  }
  if (result.resultCode != "SUCCESS") {
    return {
      errCode: result.resultCode,
      errMsg: result.errCodeDes
    }
  }

  // let params = {
  //   status: result.tradeState,
  //   modifyTime: Date.now()
  // }

  // db.collection('order').where({ outTradeNo: outTradeNo }).update({ data: params });
  // db.collection('goods_order').where({ outTradeNo: outTradeNo }).update({ data: params });


  return result
}